import React, { FC, useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { UploadOutlined } from '@ant-design/icons';
import { Form, Input, Modal, Select, Tree, UploadProps } from 'antd';
import { Button, Upload, Checkbox, message } from 'antd';
import { RouteComponentProps } from 'react-router-dom';
import { parse } from 'qs';
import Chart from './Chart';
import Son from './Son';
import { context, myUseState } from './config';
import CustomTable from './CustomTable';
import CustomTable2 from './CustomTable2';

const { DirectoryTree } = Tree;
const { Provider } = context;

const text: any =
  '<p><strong>【需求背景】</strong></p><p>&nbsp; 目前拍摄异常算法已上线，能够发现设备问题导致的异常资料问题。为整体提升资料质量、减少异常设备采集资料浪费采集机会与流量。现希望能够将发现的异常设备接入黑名单流程。</p><p>&nbsp;</p><p><strong>【需求内容】</strong></p><p>&nbsp; &nbsp; 对于拍摄异常审核中、设备相关原因导致的资料拍摄异常问题（如双屏multiwin、倒置overturn&nbsp;、拍车内incar、拍天sky&nbsp;），用高置信（confidence&gt;=99999.0）算法判定结果代替社会化审核人工结果，进入审核黑名单（90天禁止采集）。</p><p>&nbsp; &nbsp;</p>';

const data: any = {
  all: ['拍摄'],
  no: ['需求'],
};

const initTreeData = [
  {
    title: 'Expand to load',
    key: '0',
  },
  {
    title: 'Expand to load',
    key: '1',
  },
  {
    title: 'Tree Node',
    key: '2',
    isLeaf: true,
  },
];

const CustomDemo: FC<RouteComponentProps> = ({ location, history }) => {
  const [desc, setDesc] = useState<string>(text);
  const [file, setFile] = useState(null);
  const [dataC, setDataC] = useState<any[]>([]);
  const [show, setShow] = useState(false);
  const [a, setA] = useState(0);
  const [treeData, setTreeData] = useState<any>([]);
  const [isR, setIsR] = useState({});
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [testValue, setTestValue]: any = myUseState(0);

  const [b, setB] = useState(0);

  const { name = '' } = parse(location.search.substring(1));

  const [form] = Form.useForm();

  // 可监听 location 地址栏参数的变化
  // 相当于修改了地址参数/pathname/一些其他路由参数,它内部其实是修改了状态,然后就会触发重新render机制,会重新render一次当前组件
  // 所以可以监听到
  useEffect(() => {
    console.log(name);
    console.log('Father');
  }, [name]);

  useEffect(() => {
    setTimeout(() => {
      setTreeData(initTreeData);
    }, 1000);
  }, [isR]);

  useEffect(() => {
    console.log(a, 'a');
    for (let i = 0; i < 9999999; i++) {
      //
    }
    console.log(b, 'b');
  }, [a, b]);

  const onChange = (value: string[]) => {
    const colors: any = {
      all: 'green',
      no: 'red',
    };
    let newText: any = text;
    value.forEach((item) => {
      const textList: string[] = data[item];
      textList.forEach((val) => {
        newText = newText.replaceAll(
          val,
          `<span style="color:${colors[item]}">${val}</span>`
        );
      });
    });
    setDesc(newText);
  };
  // 鼠标监听,当释放鼠标的时候，调用testSelection()方法。
  document.onmouseup = function () {
    // console.log(window.getSelection()?.toString());
    // console.log(window.getSelection()?.getRangeAt(0));
  };

  const props: UploadProps = {
    name: 'file',
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    headers: {
      authorization: 'authorization-text',
    },

    beforeUpload: (file: any) => {
      setFile(file);
      return false;
    },
  };

  const uploadClick = () => {
    if (!file) {
      message.error('请选存储上传的文件');
      return;
    }
    const sd: FormData = new FormData();
    sd.append('file', file);
    fetch('https://xxx.com', {
      method: 'post',
      body: sd,
    })
      .then((ret) => ret.json)
      .then((ret) => {
        console.log(ret);
      });
  };

  const updateTreeData = (list, key, children) =>
    list.map((node) => {
      if (node.key === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  const onLoadData: any = ({ key, children }) =>
    new Promise((resolve) => {
      console.log('aksjdaskldjasdjkdls');

      setTimeout(() => {
        setTreeData((origin) =>
          updateTreeData(origin, key, [
            {
              title: 'Child Node',
              key: `${key}-0`,
              isLeaf: false,
            },
            {
              title: 'Child Node',
              key: `${key}-1`,
            },
          ])
        );
        resolve(true);
      }, 1000);
    });

  console.log(treeData, '>');

  return (
    <>
      <div>
        <h1>【文字变色DEMO】</h1>
        <Checkbox.Group onChange={onChange}>
          <Checkbox value={'all'}>显示已覆盖词</Checkbox>
          <Checkbox value={'no'}>显示未覆盖词</Checkbox>
        </Checkbox.Group>
        <div dangerouslySetInnerHTML={{ __html: desc }}></div>
      </div>
      <Upload {...props}>
        <Button icon={<UploadOutlined />}>存储当前上传的文件</Button>
      </Upload>
      <button onClick={uploadClick}>上传</button>
      <button
        onClick={() => {
          history.push({
            pathname: location.pathname,
            search: 'name=1',
          });
        }}
      >
        点我,添加url参数
      </button>
      <button
        onClick={() => {
          setDataC([
            { country: '北美', date: 1965, value: 1390.5 },
            { country: '北美', date: 1966, value: 1469.5 },
            { country: '北美', date: 1967, value: 1521.7 },
            { country: '北美', date: 1968, value: 1615.9 },
            { country: '北美', date: 1969, value: 1703.7 },
            { country: '北美', date: 1970, value: 1767.8 },
            { country: '北美', date: 1971, value: 1806.2 },
            { country: '北美', date: 1972, value: 1903.5 },
            { country: '北美', date: 1973, value: 1986.6 },
            { country: '北美', date: 1974, value: 1952 },
            { country: '北美', date: 1975, value: 1910.4 },
            { country: '北美', date: 1976, value: 2015.8 },
            { country: '北美', date: 1977, value: 2074.7 },
            { country: '北美', date: 1978, value: 2092.7 },
            { country: '北美', date: 1979, value: 2123.8 },
          ]);
        }}
      >
        设置DataC
      </button>
      <Chart data={dataC} />
      <Provider value={{ data: dataC }}>
        <Son />
      </Provider>
      <Form
        initialValues={{
          s: '我是value',
        }}
        onFinish={(v) => {
          console.log(v);
        }}
      >
        <Form.Item name="s">
          <Select
            options={[
              {
                label: '我是label',
                value: '我是value',
              },
            ]}
          />
        </Form.Item>
        <Form.Item>
          <Button htmlType="submit">Submit</Button>
        </Form.Item>
      </Form>
      <hr />
      <CustomTable />
      <button onClick={() => setShow(!show)}>123</button>
      {show && (
        <Form form={form}>
          <Form.Item name="name">
            <Input />
          </Form.Item>
        </Form>
      )}
      {/* <Modal
        visible={show}
        destroyOnClose
        onCancel={() => setShow(false)}
        title="demoModal"
      >
        <DemoModal />
      </Modal> */}
      <Modal
        visible={show}
        destroyOnClose
        onCancel={() => setShow(false)}
        title="demoModal"
      >
        {/* 关闭之后销毁了,再打开还是有之前的form的值,因为你只销毁了Form表单DOM,没有销毁 form 也就是 Form.useForm */}
        <Form form={form}>
          <Form.Item name="name">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <button
        onClick={() => {
          setTimeout(() => {
            setA((o) => o + 1);
            setB((o) => o + 1);
          }, 200);
        }}
      >
        a,b
      </button>
      <button onClick={() => setIsR({})}>setIsR</button>
      <DirectoryTree
        loadData={onLoadData}
        treeData={treeData}
        expandedKeys={expandedKeys}
        onExpand={(keys: any) => {
          setExpandedKeys(keys);
        }}
        // loadedKeys={[]}
      />
      <CustomTable2 />
      {createPortal(<div>createPortal</div>, document.body)}
      <button onClick={() => setTestValue(testValue + 1)}>
        testValue:{testValue}
      </button>
    </>
  );
};

export default CustomDemo;
